﻿using System;
using System.Linq;
using Quartz;
using Quartz.Core;
using ZilLion.Core.ConfigManager.Manager;
using ZilLion.Core.Log;
using ZilLion.TaskManager.Core.Infrastructure;
using ZilLion.TaskManager.Entity;
using ZilLion.TaskManager.Entity.Config;
using ZilLion.TaskManager.Entity.Entity;
using ZilLion.TaskManager.Repository;

namespace ZilLion.TaskManager.Core.Quartz
{
    public class ExeCustomTriggerListener : ITriggerListener
    {
        private readonly ITaskStateRespository _taskStateRespository = new TaskStateRespository();

        public ExeCustomTriggerListener(string name)
        {
            Name = name;
        }

        public string Name { get; }


        /// <inheritdoc />
        public void TriggerFired(ITrigger trigger, IJobExecutionContext context)
        {
            CustomTaskLogger.Print(Loglevel.Trace, $"{context.JobDetail.JobType.Name}在{DateTime.Now:yyyy-MM-dd HH:mm:ss} Trigger被激发 它关联的job即将被运行");
          
        }

        /// <inheritdoc />
        bool ITriggerListener.VetoJobExecution(ITrigger trigger, IJobExecutionContext context)
        {
            return false;
        }

        /// <inheritdoc />
        void ITriggerListener.TriggerMisfired(ITrigger trigger)
        {

            CustomTaskLogger.Print(Loglevel.Warn, $"{trigger.JobKey.Name}在{DateTime.Now:yyyy-MM-dd HH:mm:ss}错过触发！");

        }

        /// <inheritdoc />
        void ITriggerListener.TriggerComplete(ITrigger trigger, IJobExecutionContext context,
            SchedulerInstruction triggerInstructionCode)
        {
            //TODO 错误处理
            if (context.NextFireTimeUtc == null) return;
            var nextRunTime = TimeZoneInfo.ConvertTimeFromUtc(context.NextFireTimeUtc.Value.DateTime,
                TimeZoneInfo.Local);
            var taskid = trigger.JobKey.Name;

            #region 更新状态表

            var nodeid = ZilLionConfigurationManager.GetConfigInstance<TaskManagerCommonConfig>().ClientNo;
            var runlogresponse = _taskStateRespository.GetTaskStateById(taskid, nodeid);

            if (runlogresponse != null && runlogresponse.TaskStates != null)
            {
                var first = runlogresponse.TaskStates.FirstOrDefault();
                {
                    if (first != null)
                    {
                        first.Tasknextruntime = nextRunTime;
                        first.Tasklastruntime = DateTime.Now;
                        _taskStateRespository.ReportTaskExcuted(first);
                    }
                }
            }

            #endregion
        }
    }
}